#include "gamescene.h"

GameScene::GameScene(QWidget *parent) : QMainWindow(parent)
{
    levelIndex = 0;
    // 窗体设置，同主窗口
    this->setFixedSize(480, 788);
    this->setWindowIcon(QIcon(":/image/res/Coin0001.png"));
    this->setWindowTitle("Choose Level");
}

GameScene::GameScene(int levelNum)
{
    levelIndex = levelNum;

    // 窗体设置，同主窗口
    this->setFixedSize(480, 788);
    this->setWindowIcon(QIcon(":/image/res/Coin0001.png"));
    this->setWindowTitle(QString("Level %1").arg(levelIndex));

    // 创建菜单栏，同选择窗口
    QMenuBar *menu = menuBar();
    setMenuBar(menu);
    // 创建开始菜单
    QMenu *start = menu->addMenu("开始");
    QAction *quit = start->addAction("退出");

    connect(quit, &QAction::triggered, this, &GameScene::close);

    // 返回按钮音效
    QSound *backSound = new QSound(":/sound/res/BackButtonSound.wav", this);

    // 创建返回按钮
    MyPushButton *btn_back = new MyPushButton(":/image/res/BackButton.png",
                                              ":/image/res/BackButtonSelected.png");
    btn_back->setParent(this);
    btn_back->move(this->width() - btn_back->width(), this->height() - btn_back->height());

    // 发出信号，告知选择关卡返回
    connect(btn_back, &MyPushButton::clicked, this, [=]() {
        backSound->play();
        emit BacktoSelect();
    });

    // 显示当前关卡
    QLabel *label = new QLabel(QString("Level %1").arg(levelNum), this);
    QFont font;
    font.setFamily("Times New Roman");
    font.setPointSize(20);
    label->setFont(font);
    label->setGeometry(QRect(30, this->height() - 70, 120, 50));

    // 初始化当前关卡数据
    dataConfig config;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 4; j++)
            gameArray[i][j] = config.mData[levelIndex][i][j];

    // 翻金币音效与胜利音效
    QSound *flipSound = new QSound(":/sound/res/ConFlipSound.wav", this);
    QSound *winSound = new QSound(":/sound/res/LevelWinSound.wav", this);

    // 金币背景
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            // 绘制背景图片
            QPixmap pic(":/image/res/BoardNode.png");
            QLabel *label = new QLabel;
            label->setGeometry(0, 0, pic.width(), pic.height());
            label->setPixmap(pic);
            label->setParent(this);
            label->move(140 + i * 50, 300 + j * 50);

            // 创建金币
            QString coin_type = gameArray[i][j] == 1 ? ":/image/res/Coin0001.png"
                                                     : ":/image/res/Coin0008.png";

            Coin *coin = new Coin(coin_type);
            coin->setParent(label);
            coin->move((label->width() - coin->width()) / 2, (label->height() - coin->height()) / 2);
            coin->posX = i;
            coin->posY = j;
            coin->flag = gameArray[i][j];

            // 将金币加入到coinArray
            coinArray[i][j] = coin;

            // 点击金币，进行翻转
            connect(coin, &Coin::clicked, this, [=]() {
                flipSound->play();
                // 阻塞所有硬币，不允许再点击
                for (int i = 0; i < 4; i++)
                    for (int j = 0; j < 4; j++)
                        coinArray[i][j]->Flipable = false;

                coin->changeFlag();
                gameArray[i][j] = gameArray[i][j] == 0 ? 1 : 0;

                // 延迟翻转周围（十字）金币
                QTimer::singleShot(300, this, [=]() {
                    // 右侧
                    FlipCoin(coin->posX + 1, coin->posY);

                    // 左侧
                    FlipCoin(coin->posX - 1, coin->posY);

                    // 下侧
                    FlipCoin(coin->posX, coin->posY + 1);

                    // 上侧
                    FlipCoin(coin->posX, coin->posY - 1);

                    // 恢复其他硬币状态，允许点击
                    for (int i = 0; i < 4; i++)
                        for (int j = 0; j < 4; j++)
                            coinArray[i][j]->Flipable = true;

                    // 判断是否胜利
                    // singleShot是一个异步实现，所以判断胜利必须写在里面
                    Victory = true;
                    for (int m = 0; m < 4; m++)
                        for (int n = 0; n < 4; n++)
                            if (!coinArray[m][n]->flag) {
                                Victory = false;
                                break;
                            }

                    if (Victory) {
                        winSound->play();
                        QDialog *dlg = new QDialog(this);
                        dlg->setWindowTitle("Win");
                        dlg->setStyleSheet(
                            "background-image:url(:/image/res/LevelCompletedDialogBg.png);");
                        QPixmap pic(":/image/res/LevelCompletedDialogBg.png");
                        dlg->resize(pic.width(), pic.height());
                        dlg->setWindowFlags(Qt::Dialog | Qt::WindowCloseButtonHint);
                        dlg->setAttribute(Qt::WA_DeleteOnClose);
                        dlg->open();
                        connect(dlg, &QDialog::finished, this, &GameScene::BacktoSelect);
                    }
                });
            });
        }
    }
}

void GameScene::FlipCoin(int x, int y)
{
    if ((x > 3) || (x < 0) || (y > 3) || (y < 0)) {
        // invalid Coin Position
        return;
    }
    coinArray[x][y]->changeFlag();
    gameArray[x][y] = gameArray[x][y] == 0 ? 1 : 0;
}

void GameScene::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    // 背景
    QPixmap pic;
    pic.load(":/image/res/PlayLevelSceneBg.png");
    painter.drawPixmap(0, 0, this->width(), this->height(), pic);

    // 加载标题
    pic.load(":/image/res/Title.png");
    pic = pic.scaled(pic.width() * 0.5, pic.height() * 0.5);
    painter.drawPixmap(10, 30, pic.width(), pic.height(), pic);
}
